package com.green.common.util;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.green.common.page.Pagination;
import com.green.common.util.utils.CollectionUtils;

public class PaginationUtil {

	/**
	 * 用于分页显示 为分布控件设置公共参数
	 * 
	 * @param param
	 * @param pagination
	 */
	public static void setPaginationParams(Map<String,Object> param, Pagination<?> pagination) {
		if (param == null)
			return;
		int beginIndex = (pagination.getCurrentPage() - 1) * pagination.getPageSize();
		int endIndex = beginIndex + pagination.getItems().size();
		param.put("beginIndex", beginIndex == 0 ? 1 : beginIndex);
		param.put("endIndex", endIndex);
		param.put("currentPage", pagination.getCurrentPage());
		param.put("pageCount", pagination.getPageCount());
		param.put("pageSize", pagination.getPageSize());
		param.put("recordCount", pagination.getRecordCount());
	}

	/**
	 * 转换为 ingrid对应的数据格式
	 * 
	 * @param pagination
	 * @return
	 */
	public static Map<String, Object> toIngridData(Pagination<? extends Object> pagination) {
		final Map<String, Object> ingridData = new HashMap<String, Object>();

		ingridData.put("page", pagination.getCurrentPage());
		ingridData.put("records", pagination.getCount());
		ingridData.put("total", pagination.getPageCount());
		ingridData.put("rows", pagination.getItems());
		return ingridData;
	}

	/**
	 * 转换为 ingrid对应的数据格式
	 * 
	 * @param pagination
	 * @return
	 */
	public static Map<String, Object> toIngridData(Pagination<? extends Object> pagination, ItemConvertor itemConvertor) {
		final Map<String, Object> ingridData = new HashMap<String, Object>();

		ingridData.put("page", pagination.getCurrentPage());
		ingridData.put("records", pagination.getCount());
		ingridData.put("total", pagination.getPageCount());
		if (CollectionUtils.isEmpty(pagination.getItems())) {
			ingridData.put("rows", pagination.getItems());
		} else {
             final List<Object> list=new ArrayList<Object>();
			 for (Object obj : pagination.getItems()) {
				list.add(itemConvertor.convert(obj));
			 }
			 ingridData.put("rows", list);
		}
		return ingridData;
	}
	
	public static Map<String,Object> createRowObj(String id,List<?> cells){
		final Map<String,Object> rowObj=new HashMap<String, Object>();
		rowObj.put("id", id);
		rowObj.put("cell", cells);
		return rowObj;
	}
	
	public static Map<String,Object> createRowObj(String id,Object ...cells){
		return createRowObj(id,Arrays.asList(cells));
	}

	public static interface ItemConvertor {
		Object convert(Object obj);
	}

}
